import '../../public.dart';

class CategoryItems {
  SysGiftCardTypeEntity type;
  List<SysGiftCardCategoryEntity> list = [];
  bool isLoading = false;
  bool inted = false;

  CategoryItems(this.type);

  void updateList(List<SysGiftCardCategoryEntity> list) {
    this.list = list;
  }
}

class HomeModel extends ViewStateModel {
  final UserModel userModel;
  final List<CarouselChartEntity> bannerList = [];
  // 分类列表
  List<SysGiftCardTypeEntity> categories = [];
  // 当前选中的分类ID（默认为第一个分类）
  String selectedCategoryId = '';
  // 当前分类下的商品列表
  Map<String, CategoryItems> categoryItems = {};

  /// 加载轮播图数据
  Future<void> loadBannerData() async {
    final resp = await CarouselApi.getList();
    bannerList.addAll(resp.content ?? []);
  }

  Future<void> loadCategoryData() async {
    final response = await GiftcardApi.typetList_1();
    categories = response.content ?? [];
    // 初始化分类商品列表
    categoryItems = {
      for (var type in categories)
        type.id?.toString() ?? '': CategoryItems(type),
    };

    // 默认选中第一个分类（如果有的话）
    if (categories.isNotEmpty) {
      selectedCategoryId = categories.first.id?.toString() ?? '';
      _loadCategoryItems();
    }
  }

  /// 加载分类数据
  Future<void> _loadCategoryItems() async {
    if (selectedCategoryId.isEmpty) {
      return;
    }
    categoryItems[selectedCategoryId]?.isLoading = true;
    notifyListeners();
    final typeId = int.parse(selectedCategoryId);
    final response = await GiftcardApi.categoryListByType_2(typeId);
    categoryItems[selectedCategoryId]?.updateList(response.content ?? []);
    categoryItems[selectedCategoryId]?.isLoading = false;
    categoryItems[selectedCategoryId]?.inted = true;
    notifyListeners();
  }

  Future<void> loadCategoryItems(SysGiftCardTypeEntity type) async {
    if (selectedCategoryId == type.id?.toString()) {
      return;
    }
    selectedCategoryId = type.id?.toString() ?? '';
    await _loadCategoryItems();
  }

  Future<void> init() async {
    try {
      setBusy(true);
      await userModel.init();
      await loadBannerData();
      await loadCategoryData();
      notifyListeners();
    } catch (e) {
      setError('load data error: $e');
    } finally {
      setBusy(false);
    }
  }

  HomeModel(this.userModel);
}
